package com.CRApp.utils;

/**
 * @ClassName: JwtUtil
 * @Author : LuoFan洛樊
 * @Date : 2025/2/6 - 12:01
 * Description : TODO
 */
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "luofan-FelixAI";

    //接收业务数据,生成token并返回
    public static String genToken(Map<String, Object> claims) {
        String token = JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 12))
                .sign(Algorithm.HMAC256(KEY));
                
        System.out.println("生成token: " + token);
        System.out.println("token部分数: " + token.split("\\.").length);
        return token;
    }

    //接收token,验证token,并返回业务数据
    public static Map<String, Object> parseToken(String token) {
        // 参数检查
        if (token == null || token.isEmpty()) {
            System.out.println("Token为空");
            throw new JWTDecodeException("Token为空");
        }
        
        token = token.trim();
        System.out.println("解析token[" + token.length() + "]: " + token);
        
        try {
            // 预先解码检查
            DecodedJWT jwt = JWT.decode(token);
            if (!jwt.getClaims().containsKey("claims")) {
                System.out.println("Token不包含claims字段");
                throw new JWTDecodeException("Token格式错误: 不包含claims字段");
            }
            
            // 验证token
            DecodedJWT verifiedJwt = JWT.require(Algorithm.HMAC256(KEY))
                    .build()
                    .verify(token);
            
            // 提取claims
            Map<String, Object> claims = verifiedJwt.getClaim("claims").asMap();
            System.out.println("Token验证成功，claims: " + claims);
            return claims;
        } catch (JWTDecodeException e) {
            System.out.println("Token格式错误: " + e.getMessage());
            throw new JWTDecodeException("Token格式错误: " + e.getMessage());
        } catch (JWTVerificationException e) {
            System.out.println("Token验证失败: " + e.getMessage());
            throw e;
        } catch (Exception e) {
            System.out.println("解析Token时发生未知错误: " + e.getMessage());
            e.printStackTrace();
            throw new JWTVerificationException("Token验证失败: " + e.getMessage());
        }
    }
}
